#include <vector>

using namespace std;

class Solution {
public:

    // 123. 买卖股票的最佳时机 III
    // https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/
    const int INF = 0x3f3f3f3f;
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        
        vector<vector<int>> f(n, vector<int>(3, -INF));
        auto g = f;

        f[0][0] = -prices[0];
        g[0][0] = 0;

        for (int i = 1; i<n; ++i)
        {
            for (int j = 0; j<3; ++j)
            {
                f[i][j] = max(f[i-1][j], g[i-1][j] - prices[i]);
                g[i][j] = g[i-1][j];
                if (j >= 1)
                    g[i][j] = max(g[i][j], f[i-1][j-1] + prices[i]);
            }
        }

        return *max_element(g[n-1].begin(), g[n-1].end());
    }

    // 188. 买卖股票的最佳时机 IV
    // https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/
    int maxProfit(int k, vector<int>& prices) {
        int n = prices.size();
        const int INF = 0x3f3f3f3f;
        
        vector<vector<int>> f(n, vector<int>(k+1, -INF));
        auto g = f;

        f[0][0] = -prices[0], g[0][0] = 0;

        for (int i = 1; i<n; ++i)
        {
            for (int j = 0; j<=k; ++j)
            {
                f[i][j] = max(f[i-1][j], g[i-1][j]-prices[i]);
                g[i][j] = g[i-1][j];
                if (j >= 1)
                    g[i][j] = max(g[i-1][j], f[i-1][j-1]+prices[i]);
            }
        }

        return *max_element(g[n-1].begin(), g[n-1].end());
    }

    // 53. 最大子数组和
    // https://leetcode.cn/problems/maximum-subarray/
    int maxSubArray(vector<int>& nums) {
        int n = nums.size();
        vector<int> dp(n+1);
        for (int i = 1; i<=n; ++i)
        {
            dp[i] = max(nums[i-1], dp[i-1] + nums[i-1]);
        }

        return *max_element(dp.begin() + 1, dp.end());
    }
};

